/**
 * @description 侧边栏logo 动态头像
 */

import { hasKey, offset, siblings, toggle, toggleClass } from '@/utils/js';
import WebGL from 'three/examples/jsm/capabilities/WebGL';
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { Skin } from '../skineditor/Skin';
import { Object3D, PerspectiveCamera, Raycaster, Scene, Vector2, Vector3, WebGLRenderer } from 'three';
import { setSkin } from '@/utils/cache/localStorage';

export class SkinLogo {
    private SKIN_IMAGE: any;
    private BACKGROUND_COLOR = '#ffffff';
    public DEFAULT_SKIN_URL = "/image/skin/default_skin.png"; // 默认皮肤
    public WEBGL = WebGL.isWebGLAvailable();
    public WIDTH = 0; // 宽度
    public HEIGHT = 0; // 高度
    public MULTISAMPLING = 1;

    static instance: SkinLogo;
    public orbitControls!: OrbitControls;
    public renderer!: WebGLRenderer;
    public scene!: Scene;
    public camera!: PerspectiveCamera;
    public canvas!: HTMLElement;
    public skin!: Skin;
    public head!: Object3D;
    public INIT: boolean = false;
    public mousePos: Vector2 = new Vector2();


    constructor() {
        this.canvas = document.getElementById("canvas") as HTMLElement;

        SkinLogo.instance = this;
    }

    public init() {
        this.countRect();

        this.initScene();

        this.initRenderer();

        this.initCamera();

        this.initListener();

        this.INIT = true;

        this._initLoaded();
    }

    _initLoaded = () => { };

    initLoaded = (call: () => void) => {
        this._initLoaded = call;
    }

    private initScene() {
        this.scene = new Scene();
    }

    private initCamera() {
        this.camera = new PerspectiveCamera(45, this.WIDTH / this.HEIGHT, .1, 1e3);
        this.camera.position.x = 0;
        this.camera.position.y = 4;
        this.camera.position.z = 15;
        this.camera.lookAt(new Vector3(0, 4, 0));
    }

    private initRenderer() {

        this.renderer = new WebGLRenderer({
            alpha: !0,
            antialias: !0,
            preserveDrawingBuffer: true,
            logarithmicDepthBuffer: true,
        });


        this.renderer.setSize(this.WIDTH * this.MULTISAMPLING, this.HEIGHT * this.MULTISAMPLING);

        // 窗口重新渲染
        // this.render();

    }

    public addCanvas = (canvas: HTMLCanvasElement) => {
        canvas.append(this.renderer.domElement);
    }

    private initListener() {
        window.addEventListener('pointermove', this.onPointerMove);
    }

    private onPointerMove(event: MouseEvent) {
        let mouse = new Vector2();
        //将鼠标点击位置的屏幕坐标转换成threejs中的标准坐标
        mouse.x = (event.clientX / window.innerWidth) * 2 - 0.19;
        mouse.y = (event.clientY / window.innerHeight) * 2 - 0.165  ;
        SkinLogo.instance.mousePos = mouse;

    }

    public rotationAni = () => {
        // console.log(this.mousePos)
        let x = 2;
        let y = 2;

        let vector = new Vector3(this.mousePos.y / y, this.mousePos.x / x, 0);

        let angleX = this.mousePos.x / x * 90;
        let angleY = this.mousePos.y / y * 90;

        let angle = (angleX + angleY) / 2;
        this.head.quaternion.setFromAxisAngle(vector, Math.PI / 180 * angle);

        // this.head.rotateOnAxis(new Vector3(0, 1, 0), Math.PI / 180 * 1);
        // this.head.rotateOnAxis(new Vector3(0, 1, 0), Math.PI / 180 * 1);
    }

    // 独立引入皮肤
    public initSkin = (url?: string) => {
        console.log("皮肤加载,e:" + url);

        url = url || this.DEFAULT_SKIN_URL;

        (this.SKIN_IMAGE = new Image).src = url;

        // 导入成功 开始初始化人物模型
        this.SKIN_IMAGE.onload = () => {

            this.skin = new Skin(this.SKIN_IMAGE);

            this.head = this.skin.object.children[0];

            this._initSkinLoaded();
        }

    }

    _initSkinLoaded = () => { };

    initSkinLoaded = (call: () => void) => {
        this._initSkinLoaded = call;
    }


    // 渲染场景
    public render = () => {
        this.renderer.render(this.scene, this.camera);
    };

    /**
   * @description 逐帧渲染 frame(帧)
   */
    public frameByFrame = () => {
        requestAnimationFrame(this.frameByFrame);
        this._AnimationLoaded();

        this.rotationAni();

        this.render();
    }

    _AnimationLoaded = () => { };

    AnimationLoaded = (call: () => void) => {
        this._AnimationLoaded = call;
    }

    // 计算canvas 宽 高
    private countRect() {
        // const height = this.mobileVersion() ? 460 : 490;

        let height = (document.querySelector(".sidebar-logo-container") as any).offsetHeight;
        let width = (document.querySelector(".sidebar-logo-container") as any).offsetWidth;
        // console.log(parseInt(width) - 24)
        if (width != this.WIDTH || height != this.HEIGHT) {
            this.WIDTH = width;
            this.HEIGHT = height;
        };
        console.log(this.WIDTH, this.HEIGHT);
    }

    // 获取 鼠标坐标
    public cast_ray = (e: any, t: any, r?: any) => {
        if (!this.skin) return null;
        let i = (offset((document.getElementById("canvas") as any)) as any);
        let position = new Vector3((e - i.left) / this.WIDTH * 2 - 1, 1 - (t - i.top) / this.HEIGHT * 2, .5);
        // 将坐标转变到场景中
        position.unproject(this.camera);
        const raycaster = new Raycaster(this.camera.position, position.sub(this.camera.position).normalize()).intersectObjects([this.skin.object], !0);

    };

}
